﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Newtonsoft.Json;
using UFC.DBUtility;
using System.Data;
using log4net;
using System.Configuration;

namespace SendIndustrialNetwork
{
    public class DealWMSwayBillFeedBackService
    {
        private ILog rsLog = LogHelp.receiveSave;
        public void Excute()
        {
            string folderPath = ConfigurationManager.AppSettings["saveFilePath"].ToString();
            if (!Directory.Exists(folderPath)) return;
            // 获取指定路径下的所有文件（不包含子目录）
            string[] files = Directory.GetFiles(folderPath);
            // 遍历所有文件并输出文件名
            foreach (string file in files)
            {
                // 获取仅包含文件名（不含路径）
                string fileName = Path.GetFileName(file);
                if (!fileName.StartsWith("WMS-MES_WAYBILL_FEEDBACK-")) continue;
                string filepath = folderPath + "\\" + fileName;
                string jsonData = File.ReadAllText(filepath).Trim();
                if (jsonData.ToString() == "")
                {
                    File.Delete(filepath);
                    continue;
                };
                MES_WAYBILL_FEEDBACK(jsonData, filepath);
            }
        }
        /// <summary>
        /// 物流信息回传（仓储WMS->MES）
        /// </summary>
        /// <param name="jsonData"></param>
        public void MES_WAYBILL_FEEDBACK(string jsonData, string filePath)
        {
            try
            {
                rsLog.Info("MES开始处理物流信息回传JSON:【" + filePath + "】");
                var json = JsonConvert.DeserializeObject(jsonData);
                var jsonObj = JsonConvert.DeserializeObject<Dictionary<string, string>>(json.ToString());
                var insertSQL = @"insert into Way_Callback_WMS(MFGORDERNAME, BATCHNUM, SPECNO, WAY_NO, WAY_STATUS, PICKDATE, DLVDATE, RCVDATE {8})
                              values('{0}','{1}','{2}','{3}','{4}',to_date('{5}','yyyy-MM-dd hh24:mi:ss'),to_date('{6}','yyyy-MM-dd hh24:mi:ss'),to_date('{7}','yyyy-MM-dd hh24:mi:ss') {9})";
                var updateSQL = @"update Way_Callback_WMS way set way.WAY_STATUS='{0}' where way.MFGORDERNAME='{1}'";
                DataTable dt = OracleHelper.QueryTable(string.Format(@"select * from Way_Callback_WMS where MFGORDERNAME='{0}'", jsonObj["bizDataNo"]), null);
                var userdefs = string.Empty;
                var userdefValues = string.Empty;
                var sql = string.Empty;
                if (dt.Rows.Count == 0)
                {
                    for (var i = 1; i <= 10; i++)
                    {
                        var userDef = "userDef" + (i == 10 ? "10" : "0" + i);
                        if (jsonObj.ContainsKey(userDef)) //预留字段特殊处理
                        {
                            if (!string.IsNullOrWhiteSpace(jsonObj[userDef]))
                            {
                                userdefs += userDef + ",";
                                userdefValues += "'" + jsonObj[userDef] + "',";
                            }
                        }
                    }

                    var pickDate = jsonObj.ContainsKey("pickDate") ? ConvertToTime(jsonObj["pickDate"]) : "";
                    var dlvDate = jsonObj.ContainsKey("dlvDate") ? ConvertToTime(jsonObj["dlvDate"]) : "";
                    var rcvDate = jsonObj.ContainsKey("rcvDate") ? ConvertToTime(jsonObj["rcvDate"]) : "";
                    sql = string.Format(insertSQL, jsonObj["bizDataNo"], jsonObj["batchNum"], jsonObj.ContainsKey("opNumber") ? jsonObj["opNumber"] : "", jsonObj["waybillNo"], jsonObj["waybillStatus"], pickDate, dlvDate, rcvDate,
                        (string.IsNullOrWhiteSpace(userdefs) ? "" : "," + userdefs.TrimEnd(',')), (string.IsNullOrWhiteSpace(userdefs) ? "" : "," + userdefValues.TrimEnd(',')));
                }
                else
                {
                    sql = string.Format(updateSQL, jsonObj["waybillStatus"], jsonObj["bizDataNo"]);
                }
                var result = OracleHelper.ExecuteSql(sql) > 0;
                rsLog.Info("MES处理物流信息回传JSON结果:" + (result ? "处理成功" : "处理失败"));

            }
            catch (Exception ex)
            {
                rsLog.Info("MES处理物流信息回传JSON:" + jsonData + " 异常：" + ex.Message);
            }
            finally
            {
                File.Delete(filePath);
            }
        }

        private string ConvertToTime(string timeStamp)
        {
            if (string.IsNullOrWhiteSpace(timeStamp)) return "";
            try
            {
                DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
                long lTime = long.Parse(timeStamp + "0000");
                TimeSpan toNow = new TimeSpan(lTime);
                return dtStart.Add(toNow).ToString("yyyy-MM-dd HH:mm:ss");
            }
            catch (Exception ex)
            {

            }
            return "";
        }

    }
}
